package com.yangxk.kadmin.web.module.system.controller;

import com.yangxk.kadmin.common.beans.Result;
import com.yangxk.kadmin.common.exception.BizException;
import com.yangxk.kadmin.web.common.enumeration.ResponseCode;
import com.yangxk.upload.provider.UploadProvider;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@Slf4j
public class UploadController {

    @Autowired
    private UploadProvider uploadProvider;

    @PostMapping("/upload")
    public Result upload(@RequestParam("file") MultipartFile file) {
        if (file == null) {
            return Result.ofError(ResponseCode.ILLEGAL_PARAM);
        }

        try {

            String url = uploadProvider.upload(file.getOriginalFilename(), file.getInputStream());

            return Result.ofSuccess(url);
        } catch (IOException e) {
            log.error("上传文件失败: ", e);
            throw new BizException(ResponseCode.UPLOAD_ERROR);
        }


    }
}
